import pymysql.cursors
import logging
import uuid
from datetime import datetime
import json
from flask import request, jsonify
import system_setup
import requests
from configparser import ConfigParser
from camera_discovery import CameraDiscovery
import binascii
# 读取配置文件
conf = ConfigParser()
conf.read("setting.ini", encoding='utf-8')
# log日志
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')


# 数据库连接
def mysql():
    mydb = pymysql.connect(
        host=conf.get("mysql_settings", "host"),
        port=int(conf.get("mysql_settings", "port")),
        user=conf.get("mysql_settings", "user"),
        password=conf.get("mysql_settings", "password"),
        database='device_info',
        cursorclass=pymysql.cursors.DictCursor
    )
    return mydb


# 设备新增
def deviceAdd():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']
        number = jsons['number']
        installTime = jsons['installTime']
        position = jsons['position']
        alarmPhone = ''
        if jsons.__contains__('alarmPhone'): alarmPhone = jsons['alarmPhone']
        img = ''
        if jsons.__contains__('img'): img = jsons['img']
        install_person = ''
        if jsons.__contains__('installPerson'): install_person = jsons['installPerson']
        install_person_phone = ''
        if jsons.__contains__('installPersonPhone'): install_person_phone = jsons['installPersonPhone']
        remark = ''
        if jsons.__contains__('remark'): remark = jsons['remark']
        camera_account = ''
        if jsons.__contains__('cameraAccount'): camera_account = jsons['cameraAccount']
        camera_password = ''
        if jsons.__contains__('cameraPassword'): camera_password = jsons['cameraPassword']
        camera_ip = ''
        if jsons.__contains__('cameraIp'): camera_ip = jsons['cameraIp']
        camera_port = ''
        if jsons.__contains__('cameraPort'): camera_port = jsons['cameraPort']
        device_type = jsons['deviceType']
        device_classify = jsons['deviceClassify']
        product_id = jsons['productId']
        device_class = jsons['deviceClass']
        trans_device_code = ''
        if jsons.__contains__('trans_device_code'): trans_device_code = jsons['trans_device_code']
        is_children = jsons['is_children']
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        id = str(uuid.uuid4())
        sql = "SELECT number FROM `device_info` WHERE number = '" + jsons['number'] + "'"
        cursor.execute(sql)
        count = cursor.fetchall()
        if count.__len__() > 0:
            return jsonify(code=1, msg="设备已存在")

        sql = "insert into device_info (id,name,number,install_time,position,alarm_phone,install_person,install_person_phone,remark,current_state,img,create_time,normal_update_time,device_type,device_classify,product_id,device_class,camera_account,camera_password,camera_ip,camera_port,trans_device_code,is_children) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s)" \
              % (id, name, number, installTime, position, alarmPhone, install_person, install_person_phone, remark, '1',
                 img, creation_date, creation_date, device_type, device_classify, product_id, device_class,
                 camera_account, camera_password, camera_ip, camera_port,trans_device_code,is_children)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 设备更新
def deviceUpdate():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        cursor = mydb.cursor()
        jsons = request.json
        name = jsons['name']
        number = str(jsons['number'])
        installTime = jsons['installTime']
        position = jsons['position']
        #alarmPhone = jsons['alarmPhone']
        alarmPhone = ''
        if jsons.__contains__('alarmPhone'): alarmPhone = jsons['alarmPhone']
        img = ''
        if jsons.__contains__('img'): img = jsons['img']
        install_person = ''
        if jsons.__contains__('installPerson'): install_person = jsons['installPerson']
        install_person_phone = ''
        if jsons.__contains__('installPersonPhone'): install_person_phone = jsons['installPersonPhone']
        remark = ''
        if jsons.__contains__('remark'): remark = jsons['remark']
        device_type = jsons['deviceType']
        device_classify = jsons['deviceClassify']
        product_id = jsons['productId']
        device_class = jsons['deviceClass']
        id = jsons['id']
        camera_account = ''
        if jsons.__contains__('cameraAccount'): camera_account = jsons['cameraAccount']
        camera_password = ''
        if jsons.__contains__('cameraPassword'): camera_password = jsons['cameraPassword']
        camera_ip = ''
        if jsons.__contains__('cameraIp'): camera_ip = jsons['cameraIp']
        camera_port = ''
        if jsons.__contains__('cameraPort'): camera_port = jsons['cameraPort']
        trans_device_code = ''
        if jsons.__contains__('trans_device_code'): trans_device_code = jsons['trans_device_code']
        is_children = jsons['is_children']
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        sql = "SELECT number FROM `device_info` WHERE id = '" + jsons['id'] + "'"
        cursor.execute(sql)
        oldNumber = cursor.fetchone()
        if number != oldNumber['number']:
            sql = "SELECT number FROM `device_info` WHERE number = '" + jsons['number'] + "'"
            cursor.execute(sql)
            count = cursor.fetchall()
            if count.__len__() > 0:
                return jsonify(code=1, msg="设备已存在")
        sql = "DELETE FROM device_info WHERE id = '" + jsons['id'] + "'"
        cursor.execute(sql)
        mydb.commit()
        sql = "insert into device_info (id,name,number,install_time,position,alarm_phone,install_person,install_person_phone,remark,current_state,img,create_time,normal_update_time,device_type,device_classify,product_id,device_class,camera_account,camera_password,camera_ip,camera_port,trans_device_code,is_children) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s)" \
              % (id, name, number, installTime, position, alarmPhone, install_person, install_person_phone, remark, '1',
                 img, creation_date, creation_date, device_type, device_classify, product_id, device_class,
                 camera_account, camera_password, camera_ip, camera_port,trans_device_code,is_children)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 设备删除
def deviceDel():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            sql = "select * from device_info where id='" + jsons.get("id") + "'"
            cursor.execute(sql)
            device_info = cursor.fetchone()
            if device_info['device_type'] == '1111':
                sql = "SELECT number FROM `device_info` WHERE trans_device_code = '" + device_info['number'] + "'"
                cursor.execute(sql)
                count = cursor.fetchall()
                if count.__len__() > 0:
                    return jsonify(code=1, msg="存在子设备无法删除!")
            sql = "DELETE FROM device_info WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0
    )


# 设备详情
def deviceDetails():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('id'):
            sql = "select * from device_info where id='" + jsons.get("id") + "'"
            cursor.execute(sql)
            device_info = cursor.fetchone()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0,
        data=device_info
    )


# 设备分页列表
def deviceListPage():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            name = "AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
            number = "AND number like '%" + jsons.get("number") + "%'" if jsons.get("number") is not None else ""
            currentState = " AND current_state = '" + jsons.get("currentState") + "'" if jsons.get("currentState") is not None else ""
            deviceClassify = " AND device_classify = '" + jsons.get("deviceClassify") + "'" if jsons.get("deviceClassify") is not None else ""
            deviceClass = " AND device_class = '" + jsons.get("deviceClass") + "'" if jsons.get("deviceClass") is not None else ""
            is_children = " AND is_children = '" + jsons.get("is_children") + "'" if jsons.get("is_children") is not None else ""
            trans_device_code = " AND trans_device_code = '" + jsons.get("trans_device_code") + "'" if jsons.get("trans_device_code") is not None else ""
            sql = "SELECT *,(select `name` from device_type where device_type.id =device_info.device_type) as device_type_name,(select `name` from product where product.id =device_info.product_id) as product_name from device_info where 1=1 " + name + number + currentState + deviceClassify + deviceClass + is_children +trans_device_code+ " order by create_time desc"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['name'] = item['name']
                temp['number'] = item['number']
                temp['installTime'] = item['install_time']
                temp['position'] = item['position']
                temp['alarm_phone'] = item['alarm_phone']
                temp['install_person'] = item['install_person']
                temp['install_person_phone'] = item['install_person_phone']
                temp['remark'] = item['remark']
                temp['current_state'] = item['current_state']
                temp['img'] = item['img']
                temp['create_time'] = item['create_time']
                temp['normal_update_time'] = item['normal_update_time']
                temp['device_type'] = item['device_type']
                temp['device_type_name'] = item['device_type_name']
                temp['trans_device_code'] = item['trans_device_code']
                temp['camera_account'] = item['camera_account']
                temp['camera_password'] = item['camera_password']
                temp['camera_ip'] = item['camera_ip']
                temp['camera_port'] = item['camera_port']
                temp['device_classify'] = item['device_classify']
                temp['product_id'] = item['product_id']
                temp['product_name'] = item['product_name']
                temp['device_class'] = item['device_class']
                temp['is_children'] = item['is_children']
                temp['trans_device_code'] = item['trans_device_code']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1, msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 设备分类列表
def deviceClassList():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('type'):
            sql = "SELECT * from device_class where type = '" + jsons['type'] + "'"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
        else:
            return jsonify(code=1, msg="缺少必要参数type")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 设备类型列表
def deviceTypeList():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('deviceClassId'):
            sql = "SELECT * from device_type where device_class_id = '" + jsons['deviceClassId'] + "'"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
        else:
            return jsonify(code=1, msg="缺少必要参数deviceClassId")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 产品列表
def productList():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('deviceClassId'):
            sql = "SELECT * from product where device_class_id = '" + jsons['deviceClassId'] + "'"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
        else:
            return jsonify(code=1, msg="缺少必要参数deviceClassId")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 获取rtmp
def getRtmp():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('number'):
            sql = "SELECT * from device_info where number = '" + jsons['number'] + "' and device_class = '1001'"
            cursor.execute(sql)
            device = cursor.fetchone()
            if device is None: return jsonify(code=1, msg="设备不存在")
            cmd = ''
            rtmp = ''
            if ':' in jsons['ip_addr']:

                cmd = "nsenter -m -n -t 1 docker run -tdi --network host --rm --name " + device['number'] + " srs:encoder ffmpeg -i rtsp://" + \
                      device['camera_account'] + ":" + device['camera_password'] + "@" + device['camera_ip'] + ":" + device[
                          'camera_port'] + "/media/1 -c copy -f flv rtmp://gw.wisdiot.com:9008/live/rtmp/" + device['number']
                rtmp = "rtmp://gw.wisdiot.com:9008/live/rtmp/" + device['number']
            else:
                cmd = "nsenter -m -n -t 1 docker run -tdi --network host --rm --name "+device['number']+" srs:encoder ffmpeg -i rtsp://"+device['camera_account']+":"+device['camera_password']+"@"+device['camera_ip']+":"+device['camera_port']+"/media/1 -c copy -f flv rtmp://"+jsons['ip_addr']+":1935/live/rtmp/"+device['number']
                rtmp = "rtmp://"+jsons['ip_addr']+":1935/live/rtmp/" + device['number']
            headers = {
                "Content-Type": "application/json; charset=UTF-8"
            }
            url = "http://127.0.0.1:8001/rest/v1/cmd/run"
            pyload = {"cmd": cmd}
            response = requests.post(url, data=json.dumps(pyload), headers=headers, timeout=5).text
            logging.debug("response:%s" % response)
        else:
            return jsonify(code=1, msg="缺少必要参数number")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rtmp
        # data="rtmp://192.168.0.99:1935/live/"+device['number']
    )


# 关闭rtmp流
def closeRtmp():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('number'):
            sql = "SELECT * from device_info where number = '" + jsons['number'] + "' and device_class = '1001'"
            cursor.execute(sql)
            device = cursor.fetchone()
            if device is None: return jsonify(code=1, msg="设备不存在")
            cmd = "docker stop " + device['number']
            headers = {
                "Content-Type": "application/json; charset=UTF-8"
            }
            url = "http://127.0.0.1:8001/rest/v1/cmd/run"
            pyload = {"cmd": cmd}
            response = requests.post(url, data=json.dumps(pyload), headers=headers, timeout=5).text
            logging.debug("response:%s" % response)
        else:
            return jsonify(code=1, msg="缺少必要参数number")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 获取
def device_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        sql = ""
        deviceClassify = " AND device_classify = '" + jsons.get("deviceClassify") + "'" if jsons.get(
            "deviceClassify") is not None else ""
        deviceClass = " AND device_class = '" + jsons.get("deviceClass") + "'" if jsons.get(
            "deviceClass") is not None else ""
        sql = "SELECT current_state,COUNT(current_state) AS count FROM device_info where 1=1 " + deviceClassify + deviceClass + " GROUP BY current_state"
        cursor.execute(sql)
        device_info_list = cursor.fetchall()
        all_count = 0
        json_data = {}
        flag = jsons.__contains__('deviceClassify')
        count = 0
        # if flag:
        #     if jsons.get("deviceClass") == '2001':
        #         count = 4000
        # else:
        #     count = 4000
        json_data['on-line'] = 0
        json_data['off-line'] = 0
        for device in device_info_list:
            if device['current_state'] == '1':
                json_data['on-line'] = device['count'] + count
            elif device['current_state'] == '3':
                json_data['off-line'] = device['count']
            all_count = all_count + device['count']
        json_data['all_count'] = all_count + count
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=json_data
    )


# 获取产品数量
def product_count():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        sql = "SELECT COUNT(id) as count FROM product"
        cursor.execute(sql)
        product_count = cursor.fetchone()
        json_data = {}
        json_data['normal'] = product_count['count']
        json_data['disable'] = 0
        json_data['all_count'] = product_count['count']
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=json_data
    )


# 获取视频设备列表
def video_device_List():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        sql = "SELECT `name`,number,camera_ip,camera_port,camera_account,camera_password FROM device_info WHERE device_class = '1001' and device_type = '2001'"
        cursor.execute(sql)
        cur_data = cursor.fetchall()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 更新设备状态
def update_device_currentState(jsonData):
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        currentState = jsonData['currentState']
        normal_update_time = jsonData['time']
        number = jsonData['number']
        sql = "UPDATE device_info SET current_state ='" + currentState + "',normal_update_time ='" + normal_update_time + "'" + " WHERE number = '" + number + "'"
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()
    return jsonify(
        msg="success",
        code=0
    )


# 消防部件新增、编辑
def component_add_update():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']
        number = jsons['number']
        position = jsons['position']
        img = ''
        if jsons.__contains__('img'): img = jsons['img']
        remark = ''
        if jsons.__contains__('remark'): remark = jsons['remark']
        part_type = jsons['part_type']
        part_type_name = jsons['part_type_name']
        trans_device_code = jsons['trans_device_code']
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        id = ''
        if jsons.__contains__('id'):
            if id is None or id == '': return jsonify(code=1, msg="id不能为空!")
            sql = "SELECT number FROM fire_fighting_component WHERE id = '" + id + "'"
            cursor.execute(sql)
            old_number = cursor.fetchone()
            if number != old_number['number']:
                sql = "SELECT number FROM fire_fighting_component WHERE number = '" + number + "'"
                cursor.execute(sql)
                count = cursor.fetchall()
                if count.__len__() > 0:
                    return jsonify(code=1, msg="部件已存在")
            sql = "DELETE FROM fire_fighting_component WHERE id = '" + id + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            id = str(uuid.uuid4())
            sql = "SELECT number FROM fire_fighting_component WHERE number = '" + number + "'"
            cursor.execute(sql)
            count = cursor.fetchall()
            if count.__len__() > 0:
                return jsonify(code=1, msg="部件已存在")
        sql = "insert into fire_fighting_component (id,name,number,position,current_state,img,create_time,normal_update_time,part_type,part_type_name,trans_device_code,remark) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
              % (id, name, number, position, '1', img, creation_date, creation_date, part_type, part_type_name,
                 trans_device_code, remark)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 消防部件删除
def component_del():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            if jsons['id'] is None or jsons['id'] == '': return jsonify(code=1, msg="id不能为空!")
            sql = "DELETE FROM fire_fighting_component WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0
    )


# 消防部件分页列表
def component_list_page():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            trans_device_code = " AND trans_device_code = '" + jsons.get("trans_device_code") + "'" if jsons.get(
                "trans_device_code") is not None else ""
            name = " AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
            number = " AND number like '%" + jsons.get("number") + "%'" if jsons.get("number") is not None else ""
            currentState = " AND current_state = '" + jsons.get("current_state") + "'" if jsons.get(
                "current_state") is not None else ""
            position = " AND position like '%" + jsons.get("position") + "%'" if jsons.get(
                "position") is not None else ""

            sql = "SELECT * from fire_fighting_component where 1=1 " + trans_device_code + trans_device_code + name + number + currentState + position + " order by create_time desc"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['name'] = item['name']
                temp['number'] = item['number']
                temp['position'] = item['position']
                temp['current_state'] = item['current_state']
                temp['img'] = item['img']
                temp['create_time'] = item['create_time']
                temp['normal_update_time'] = item['normal_update_time']
                temp['part_type'] = item['part_type']
                temp['part_type_name'] = item['part_type_name']
                temp['trans_device_code'] = item['trans_device_code']
                temp['remark'] = item['remark']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1, msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 部件类型列表
def part_type_list():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        name = " AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
        sql = "SELECT * from part_type where 1=1 " + name
        cursor.execute(sql)
        cur_data = cursor.fetchall()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 视频分析通道新增、编辑
def camera_channel_add_update():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']
        number = jsons['number']
        position = jsons['position']
        img = ''
        if jsons.__contains__('img'): img = jsons['img']
        remark = ''
        if jsons.__contains__('remark'): remark = jsons['remark']
        camera_account = jsons['camera_account']
        camera_password = jsons['camera_password']
        camera_ip = jsons['camera_ip']
        camera_port = jsons['camera_port']
        aibox_number = jsons['aibox_number']
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        id = ''
        if jsons.__contains__('id'):
            if id is None or id == '': return jsonify(code=1, msg="id不能为空!")
            sql = "SELECT number FROM camera_channel WHERE id = '" + id + "'"
            cursor.execute(sql)
            old_number = cursor.fetchone()
            if number != old_number['number']:
                sql = "SELECT number FROM camera_channel WHERE number = '" + number + "'"
                cursor.execute(sql)
                count = cursor.fetchall()
                if count.__len__() > 0:
                    return jsonify(code=1, msg="通道已存在")
            sql = "DELETE FROM camera_channel WHERE id = '" + id + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            id = str(uuid.uuid4())
            sql = "SELECT number FROM camera_channel WHERE number = '" + number + "'"
            cursor.execute(sql)
            count = cursor.fetchall()
            if count.__len__() > 0:
                return jsonify(code=1, msg="通道已存在")
        sql = "insert into camera_channel (id,name,number,position,current_state,img,create_time,normal_update_time,camera_account,camera_password,camera_ip,camera_port,aibox_number,remark) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s')" \
              % (id, name, number, position, '1', img, creation_date, creation_date, camera_account, camera_password,
                 camera_ip, camera_port, aibox_number, remark)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 视频分析通道删除
def camera_channel_del():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            if jsons['id'] is None or jsons['id'] == '': return jsonify(code=1, msg="id不能为空!")
            sql = "DELETE FROM camera_channel WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 再关闭数据库连接
    return jsonify(
        msg="success",
        code=0
    )


# 视频分析通道列表
def camera_channel_list():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('aibox_number'):
            aibox_number = " AND aibox_number = '" + jsons.get("aibox_number") + "'" if jsons.get(
                "aibox_number") is not None else ""
            name = " AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
            number = " AND number like '%" + jsons.get("number") + "%'" if jsons.get("number") is not None else ""
            position = " AND position like '%" + jsons.get("position") + "%'" if jsons.get(
                "position") is not None else ""
            sql = "SELECT * from camera_channel where 1=1 " + aibox_number + number + name + position
            cursor.execute(sql)
            cur_data = cursor.fetchall()
        else:
            return jsonify(code=1, msg="缺少必要参数aibox_number")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )


# 通知新增
def communicationAdd():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('name') and jsons.__contains__('phone') and jsons.__contains__('type'):
            sql = "SELECT phone FROM communication WHERE phone = '" + jsons['phone'] + "'and `type` = " + str(
                jsons['type'])
            cursor.execute(sql)
            count = cursor.fetchall()
            if count.__len__() > 0:
                return jsonify(code=1, msg="此手机号已存在同一类型的通知")
            # 名称
            name = jsons['name']
            if name == '': return jsonify(code=1, msg="name 不能为null")
            # 电话
            phone = jsons['phone']
            if phone == '': return jsonify(code=1, msg="phone 不能为null")
            # 类型
            type = jsons['type']
            if type == '': return jsonify(code=1, msg="type 不能为null")
            remark = ''
            if jsons.__contains__('remark'): remark = jsons['remark']
            id = str(uuid.uuid4())
            sql = "insert into communication (id,name,phone,type,remark) values('%s','%s',%s,%s,'%s')" % (id, name, phone, type,remark)
            insert = cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数name、phone、type")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 通知编辑
def communicationUpdate():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('name') and jsons.__contains__('phone') and jsons.__contains__('type') and jsons.__contains__('id'):
            sql = "SELECT phone FROM communication WHERE phone = '" + jsons['phone'] + "'and `type` = " + str(jsons['type'])
            cursor.execute(sql)
            old_phone = cursor.fetchone()
            if jsons['phone'] != old_phone['phone']:
                sql = "SELECT phone FROM communication WHERE phone = '" + jsons['phone'] + "'and `type` = " + str(jsons['type'])
                cursor.execute(sql)
                count = cursor.fetchall()
                if count.__len__() > 0:
                    return jsonify(code=1, msg="此手机号已存在同一类型的通知")
            # 名称
            name = jsons['name']
            if name == '': return jsonify(code=1, msg="name 不能为null")
            # 电话
            phone = jsons['phone']
            if phone == '': return jsonify(code=1, msg="phone 不能为null")
            # 类型
            type = jsons['type']
            if type == '': return jsonify(code=1, msg="type 不能为null")
            remark = ''
            if jsons.__contains__('remark'): remark = jsons['remark']
            id = jsons['id']
            if id == '': return jsonify(code=1, msg="id 不能为null")
            sql = "UPDATE communication SET name = '%s',phone = '%s',remark = '%s',type = %s where id = '%s'" % (name, phone,remark, type, id)
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数name、phone、type,id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 通知删除
def communicationDel():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            id = jsons['id']
            if id == '': return jsonify(code=1, msg="id 不能为null")
            sql = "DELETE FROM communication WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0
    )


# 通知配置分页列表
def communication_list_page():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            name = " AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
            phone = " AND phone like '%" + jsons.get("phone") + "%'" if jsons.get("phone") is not None else ""
            type = " AND type = '" + jsons.get("type") + "'" if jsons.get("type") is not None else ""

            sql = "SELECT * from communication where 1=1 " + name + phone + type
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['name'] = item['name']
                temp['phone'] = item['phone']
                temp['type'] = item['type']
                temp['remark'] = item['remark']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1, msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 通讯记录分页列表
def communication_record_list_page():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            phone = " AND phone = '" + jsons.get("phone") + "'" if jsons.get("phone") is not None else ""
            type = " AND type = '" + jsons.get("type") + "'" if jsons.get("type") is not None else ""

            sql = "SELECT * from communication_record where 1=1 " + phone + type
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['phone'] = item['phone']
                temp['number'] = item['number']
                temp['type'] = item['type']
                temp['time'] = item['time']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1, msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 获取局域网内onvif协议摄像头IP
def get_onvif_camera_ip():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    try:
        # 获取IP
        camera_ip = CameraDiscovery.ws_discovery()
        # 返回数据
        lst = list()
        for ip in camera_ip:
            lst.append(str(ip).strip(":"))
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    return jsonify(
        msg="success",
        code=0,
        data=lst
    )


# 批量插入onvif设备数据
def batch_insert_onvif_device():
    # response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    # token = json.loads(response.data)
    # if token['code'] == 1:
    #     return jsonify(
    #         msg=token['msg'],
    #         code=1
    #     )
    # elif token['code'] == 401:
    #     return jsonify(
    #         msg=token['msg'],
    #         code=token['code']
    #     )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']
        number = jsons['number']
        installTime = jsons['installTime']
        position = jsons['position']
        alarmPhone = ''
        if jsons.__contains__('alarmPhone'): alarmPhone = jsons['alarmPhone']
        img = ''
        if jsons.__contains__('img'): img = jsons['img']
        install_person = ''
        if jsons.__contains__('installPerson'): install_person = jsons['installPerson']
        install_person_phone = ''
        if jsons.__contains__('installPersonPhone'): install_person_phone = jsons['installPersonPhone']
        remark = ''
        if jsons.__contains__('remark'): remark = jsons['remark']
        camera_account = ''
        if jsons.__contains__('cameraAccount'): camera_account = jsons['cameraAccount']
        camera_password = ''
        if jsons.__contains__('cameraPassword'): camera_password = jsons['cameraPassword']
        camera_ip = ''
        if jsons.__contains__('cameraIp'): camera_ip = jsons['cameraIp']
        camera_port = ''
        if jsons.__contains__('cameraPort'): camera_port = jsons['cameraPort']
        device_type = jsons['deviceType']
        device_classify = jsons['deviceClassify']
        product_id = jsons['productId']
        device_class = jsons['deviceClass']
        trans_device_code = ''
        if jsons.__contains__('trans_device_code'): trans_device_code = jsons['trans_device_code']
        is_children = jsons['is_children']
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        id = str(uuid.uuid4())
        sql = "SELECT number FROM `device_info` WHERE number = '" + jsons['number'] + "'"
        cursor.execute(sql)
        count = cursor.fetchall()
        if count.__len__() > 0:
            return jsonify(code=1, msg="设备已存在")

        sql = "insert into device_info (id,name,number,install_time,position,alarm_phone,install_person,install_person_phone,remark,current_state,img,create_time,normal_update_time,device_type,device_classify,product_id,device_class,camera_account,camera_password,camera_ip,camera_port,trans_device_code,is_children) values('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s)" \
              % (id, name, number, installTime, position, alarmPhone, install_person, install_person_phone, remark, '1',
                 img, creation_date, creation_date, device_type, device_classify, product_id, device_class,
                 camera_account, camera_password, camera_ip, camera_port,trans_device_code,is_children)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 组态应用新增
def application_add():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']

        describe = ''
        if jsons.__contains__('describe'): describe = jsons['describe']

        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        id = str(uuid.uuid4())
        sql = "insert into application (id,name,`describe`,creation_date) values('%s','%s','%s','%s')" % (id, name, describe, creation_date)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 组态应用更新
def application_update():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        name = jsons['name']
        id = jsons['id']
        describe = ''
        if jsons.__contains__('describe'): describe = jsons['describe']
        sql = "DELETE FROM application WHERE id = '" + jsons['id'] + "'"
        cursor.execute(sql)
        mydb.commit()
        # 创建日期
        creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        sql = "insert into application (id,name,`describe`,creation_date) values('%s','%s','%s','%s')" % (id, name, describe, creation_date)
        insert = cursor.execute(sql)
        mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 组态应用删除
def application_del():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        if jsons.__contains__('id'):
            sql = "DELETE FROM application WHERE id = '" + jsons['id'] + "'"
            cursor.execute(sql)
            mydb.commit()
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 组态应用分页列表
def application_list_page():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('page') and jsons.__contains__('limit'):
            page = jsons.get("page")
            limit = jsons.get("limit")
            name = "AND name like '%" + jsons.get("name") + "%'" if jsons.get("name") is not None else ""
            sql = "SELECT * from application where 1=1 " + name +" order by creation_date desc"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
            items = []
            for item in cur_data[int(limit) * (int(page) - 1):int(limit) * int(page)]:
                temp = {}
                temp['id'] = item['id']
                temp['name'] = item['name']
                temp['describe'] = item['describe']
                temp['creation_date'] = item['creation_date']
                items.append(temp)
            rlt_data = {}
            num = len(cur_data)
            rlt_data["totalSize"] = num
            rlt_data["pages"] = num // int(limit) + 1
            rlt_data["pageSize"] = limit
            rlt_data["Items"] = items
            rlt_data["currentPage"] = page
            rlt_data["currentSize"] = limit
            if int(page) == rlt_data["pages"]:
                rlt_data["currentSize"] = num % int(limit)
        else:
            return jsonify(code=1, msg="缺少必要参数page、limit")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=rlt_data
    )


# 组态应用数据保存
def application_data_preserve():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.json
        data = request.data.decode(encoding='utf-8', errors='strict')
        print(data)
        if jsons.__contains__('application_id'):
            application_id = jsons['application_id']
            sql = "DELETE FROM application_data WHERE application_id = '" + application_id + "'"
            cursor.execute(sql)
            mydb.commit()
            # 创建日期
            creation_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            id = str(uuid.uuid4())
            sql = "insert into application_data (id,json,creation_date,application_id) values('%s','%s','%s','%s')" % (id,data,creation_date,application_id)
            insert = cursor.execute(sql)
            mydb.commit()
        else:
            return jsonify(code=1, msg="缺少必要参数 application_id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0
    )


# 组态应用数据详情
def application_data_details():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('application_id'):
            sql = "select * from application_data where application_id='" + jsons.get("application_id") + "'"
            cursor.execute(sql)
            data = cursor.fetchone()
        else:
            return jsonify(code=1, msg="缺少必要参数 application_id")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭数据库
    return jsonify(
        msg="success",
        code=0,
        data=data
    )


# 设备平时数据选项
def device_normal_items():
    response = system_setup.getDecodeToken(request.headers.get("Authorization", "")[7:])
    token = json.loads(response.data)
    if token['code'] == 1:
        return jsonify(
            msg=token['msg'],
            code=1
        )
    elif token['code'] == 401:
        return jsonify(
            msg=token['msg'],
            code=token['code']
        )
    mydb = mysql()
    mydb.connect()
    cursor = mydb.cursor()
    try:
        jsons = request.args
        if jsons.__contains__('pid') and jsons.__contains__('device_class'):
            sql = "SELECT * from device_normal_items where pid = '" + jsons['pid'] + "' and device_class = '"+ jsons['device_class'] + "'"
            cursor.execute(sql)
            cur_data = cursor.fetchall()
        else:
            return jsonify(code=1, msg="缺少必要参数type")
    except Exception as e:
        print(e)
        return jsonify(
            code=1,
            msg="Server internal error"
        )
    finally:
        cursor.close()  # 关闭游标
        mydb.close()  # 关闭连接
    return jsonify(
        msg="success",
        code=0,
        data=cur_data
    )
